import React, { useReducer } from 'react';
import { useDeepCompareEffect } from 'ahooks';
import { Pagination, Menu, Icon, Modal, Input } from 'antd';
import last from 'lodash/last';
import findIndex from 'lodash/findIndex';
import { getCurrentGroups, getCurrentGroup } from '../utils';

function reducer(state, action) {
  const { type, payload } = action;

  if (type === 'sync_props') {
    return {
      ...state,
      page: payload.page,
    };
  }

  if (type === 'change_page') {
    return {
      ...state,
      page: payload.page,
    };
  }

  if (type === 'search') {
    return {
      ...state,
      keyword: payload.keyword,
    };
  }

  throw new Error();
}

function getPage(current, groupName, pageSize) {
  const currentGroups = getCurrentGroups(current);

  const index = findIndex(currentGroups, { groupName });

  if (index !== -1) {
    return Math.ceil((index + 1) / pageSize);
  }

  return 1;
}

function InstanceList({ onSelect, onRemove, current, groupName }) {
  const [state, dispatch] = useReducer(reducer, {
    page: getPage(current, groupName, 5),
    pageSize: 5,
  });

  useDeepCompareEffect(() => {
    if (current && groupName) {
      dispatch({
        type: 'change_page',
        payload: {
          page: getPage(current, groupName, 5),
        },
      });
    }
  }, [groupName, current]);

  // 搜索功能
  const totoalData = getCurrentGroups(current).filter(k => {
    if (state.keyword) {
      return k.groupName.toLocaleLowerCase().indexOf(state.keyword) !== -1;
    }
    return true;
  });

  const from = (state.page - 1) * state.pageSize;

  const to = from + state.pageSize;

  const data = totoalData.slice(from, to);

  return (
    <div className="padding ant-dropdown-menu">
      <Input.Search
        placeholder="搜索"
        onChange={e => dispatch({ type: 'search', payload: { keyword: e.target.value } })}
      />

      <Pagination
        simple
        className="margin-top text-center"
        current={state.page}
        pageSize={state.pageSize}
        total={totoalData.length}
        onChange={page => dispatch({ type: 'change_page', payload: { page } })}
      />
      <Menu
        selectedKeys={[getCurrentGroup(current).groupName]}
        style={{ borderRight: 0 }}
        // className="ant-dropdown-menu"
      >
        {data.map((k, i) => (
          <Menu.Item
            key={k.groupName || i}
            className="ant-dropdown-menu-item"
            style={{ margin: '2px 0', height: '30px', lineHeight: '30px' }}
          >
            <a
              onClick={e => {
                e.preventDefault();
                onSelect(last(k.indexes));
              }}
              className="clearfix"
            >
              {k.groupName || `副本${i}`}

              <Icon
                type="close"
                className="text-danger pull-right"
                style={{ marginTop: '6px', marginRight: 0, padding: '4px' }}
                onClick={e => {
                  e.stopPropagation();

                  Modal.confirm({
                    content: `确定删除副本【${k.groupName}】及其子节点在当前分支下的副本`,
                    onOk() {
                      onRemove(k);
                    },
                  });
                }}
              />
            </a>
          </Menu.Item>
        ))}
      </Menu>
    </div>
  );
}

export default InstanceList;
